package com.example.musicapp.viewmodel

import android.media.AudioManager
import android.media.MediaPlayer
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.musicapp.model.Song
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.isActive
import kotlinx.coroutines.CoroutineScope

class MusicViewModel : ViewModel() {
    private val _currentSong = MutableLiveData<Song>()
    val currentSong: LiveData<Song> = _currentSong

    private val _isPlaying = MutableLiveData(false)
    val isPlaying: LiveData<Boolean> = _isPlaying

    private val _playlist = MutableLiveData<List<Song>>()
    val playlist: LiveData<List<Song>> = _playlist

    private var currentSongIndex = -1

    private val _currentProgress = MutableLiveData<Int>()
    val currentProgress: LiveData<Int> = _currentProgress

    private val _duration = MutableLiveData<Int>()
    val duration: LiveData<Int> = _duration

    // 模拟播放进度的协程作业
    private var progressJob: Job? = null

    // 添加 MediaPlayer
    private var mediaPlayer: MediaPlayer? = null

    fun setPlaylist(songs: List<Song>) {
        _playlist.value = songs
        // 如果当前没有正在播放的歌曲，则自动加载第一首歌
        if (_currentSong.value == null && songs.isNotEmpty()) {
            // 只设置当前歌曲信息，不自动播放
            _currentSong.value = songs[0]
            currentSongIndex = 0
            // 预加载 MediaPlayer，但不自动播放
            prepareMediaPlayer(songs[0])
        }
    }

    private fun prepareMediaPlayer(song: Song) {
        try {
            // 在创建新的 MediaPlayer 之前先释放旧的
            mediaPlayer?.apply {
                if (isPlaying) {
                    stop()
                }
                reset()
                release()
            }
            mediaPlayer = MediaPlayer().apply {
                setDataSource("http://121.37.40.55:3000/music/${song.id}.mp3")
                // 设置缓冲大小，提高加载速度
                setOnBufferingUpdateListener { _, percent ->
                    // 可以在这里添加缓冲进度的处理
                }
                prepareAsync()
                setOnPreparedListener {
                    _duration.value = duration / 1000
                    _currentProgress.value = 0
                }
                setOnCompletionListener {
                    playNext()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun playSong(song: Song) {
        try {
            // 在播放新歌之前先停止当前播放
            mediaPlayer?.apply {
                if (isPlaying) {
                    stop()
                }
                reset()
                release()
            }

            // 显示迷你播放器（通过 LiveData 通知 Activity）
            _currentSong.value = song
            
            mediaPlayer = MediaPlayer().apply {
                setAudioStreamType(AudioManager.STREAM_MUSIC)
                try {
                    setDataSource("http://121.37.40.55:3000/music/${song.id}.mp3")
                    prepareAsync()
                    setOnPreparedListener {
                        start()
                        _isPlaying.value = true
                        currentSongIndex = _playlist.value?.indexOf(song) ?: -1
                        _duration.value = duration / 1000
                        _currentProgress.value = 0
                        startProgressUpdate()
                    }
                    setOnCompletionListener {
                        playNext()
                    }
                    setOnErrorListener { _, what, extra ->
                        android.util.Log.e("MusicViewModel", "MediaPlayer error: what=$what, extra=$extra")
                        _isPlaying.value = false
                        stopProgressUpdate()
                        true
                    }
                } catch (e: Exception) {
                    android.util.Log.e("MusicViewModel", "Error setting data source", e)
                    _isPlaying.value = false
                    stopProgressUpdate()
                }
            }
        } catch (e: Exception) {
            android.util.Log.e("MusicViewModel", "Error in playSong", e)
            _isPlaying.value = false
            stopProgressUpdate()
        }
    }

    fun togglePlayPause() {
        if (_isPlaying.value == true) {
            mediaPlayer?.pause()
        } else {
            mediaPlayer?.start()
        }
        _isPlaying.value = _isPlaying.value?.not()
        if (_isPlaying.value == true) {
            startProgressUpdate()
        } else {
            stopProgressUpdate()
        }
    }

    fun playNext() {
        _playlist.value?.let { songs ->
            currentSongIndex = if (currentSongIndex < songs.size - 1) {
                currentSongIndex + 1
            } else {
                0  // 如果是最后一首歌，则返回到第一首
            }
            // 播放下一首歌
            playSong(songs[currentSongIndex])
        }
    }

    fun playPrevious() {
        _playlist.value?.let { songs ->
            currentSongIndex = if (currentSongIndex > 0) {
                currentSongIndex - 1
            } else {
                songs.size - 1  // 如果是第一首歌，则切换到最后一首
            }
            // 播放上一首歌
            playSong(songs[currentSongIndex])
        }
    }

    fun seekTo(position: Int) {
        mediaPlayer?.seekTo(position * 1000) // 转换为毫秒
        _currentProgress.value = position
    }

    private fun startProgressUpdate() {
        progressJob?.cancel()
        progressJob = viewModelScope.launch {
            while (isActive && _isPlaying.value == true) {
                delay(1000)
                mediaPlayer?.let { player ->
                    val currentPosition = player.currentPosition / 1000  // 转换为秒
                    _currentProgress.value = currentPosition
                }
            }
        }
    }

    private fun stopProgressUpdate() {
        progressJob?.cancel()
        progressJob = null
    }

    override fun onCleared() {
        super.onCleared()
        stopProgressUpdate()
        mediaPlayer?.release()
        mediaPlayer = null
    }
} 